<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as BaseController;
use App\Jobs\OrderSubmit;
use App\Libs\PhpOffice\Excel;
use App\Repository\CatchConf\DouYinCatchRepository as model;
use App\Repository\Order\OrderLogRepository as logModel;
use App\Repository\Product\GoodsRepository;
use App\Repository\Shop\SuppilerRepository as supp;
use App\Repository\UploadRepository;
use App\Repository\UpThree\MainOrderRepostition;
use Illuminate\Http\Request;

// 分销商
class CatchDouyinOrderController extends BaseController
{
    private $repoist;
    private $disModel;
    private $logModel;
    private $goodsModel;

    public function __construct(model $model, supp $supp, logModel $logModel, GoodsRepository $GoodsRepository)
    {
        $this->repoist = $model;
        $this->disModel = $supp;
        $this->logModel = $logModel;
        $this->goodsModel = $GoodsRepository;
    }

    public function store(Request $request)
    {
        return $this->repoist->add($request);
    }

    public function index(Request $request)
    {
        $where = [];
        if (($request->has('status')) && $request->get('status') != '') {
            $where['where']['status'] = $request->get('status');
        }
        if (empty($request->get('user')->role_id) || $request->get('user')->role_id != 1) {
            $where['where']['shop_id'] = $request->get('user')->shop_id;
        }
        if (!empty($request->get('shop_id'))) {
            $where['like']['shop_id_str'] = $request->get('user')->shop_id . '.' . $request->get('shop_id');
        }
        if (!empty($request->get('goods_code'))) {
            $where['like']['goods_code'] = $request->get('goods_code');
        }
        if (!empty($request->get('dist_orderno'))) {
            $where['where']['dist_orderno'] = trim($request->get('dist_orderno'), ' ');
        }
        if (!empty($request->get('identity'))) {
            $where['where']['identity'] = trim($request->get('identity'), ' ');
        }
        //店铺名称
        if (!empty($request->get('dist'))) {
            $where['where']['dist_id'] = trim($request->get('dist'), ' ');
        }
        if (!empty($request->get('iccid'))) {
            $where['where']['iccid'] = $request->get('iccid');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('express_number'))) {
            $where['where']['express_number'] = $request->get('express_number');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('contact'))) {
            $where['where']['contact'] = $request->get('contact');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('name'))) {
            $where['where']['name'] = $request->get('name');
            // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
        }
        if (!empty($request->get('douyin_name'))) {
            $where['where']['douyin_name'] = $request->get('douyin_name');
        }
        if (!empty($request->get('three_msg'))) {
            $where['like']['three_msg'] = $request->get('three_msg');
        }
        //时间验证
        if (!empty($request->get('params'))) {
            $time = $request->get('params');
            $where['between'] = ['created_at' => [$time['beginTime'], $time['endTime']]];
        }
        // var_dump($where);

        $where['limit']['start'] = ($request->get('pageNum') - 1) * $request->get('pageSize');
        $where['limit']['number'] = !empty($request->get('pageSize')) ? $request->get('pageSize') : 10;
        // DB::connection()->enableQueryLog();
        // var_dump($where);
        $data = $this->repoist->index($where);
        // $logs = DB::getQueryLog();
        // var_dump($logs);

        return $data;
    }

//修改skumark_remark内容
    public function ip138SkumarkRemarkApiBackSave(Request $request)
    {
        $where = [
            'id' => $request->get('id')
        ];
        $data = [
            'skumark_remark' => $request->get('skumark_remark')
        ];
        return $this->repoist->edit($where, $data);
    }

    public function save(Request $request)
    {
        if (!$request->get('id')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $where = [
            'id' => $request->get('id'),
            // 'shop_id' => $request->user->shop_id
        ];
        return $this->repoist->edit($where, $request);
    }

    public function show(Request $request, $id)
    {
        $where = [
            'id' => $id
        ];
        //查询一条数据
        $field = ['*'];
        $return = $this->repoist->getOne($where, $field);
        if (!empty($return->identity)) {
            unset($return->identity);
        }
        return $this->returnMsg(200, '查询成功', $return);
    }

    public function showOne($id)
    {
        $where = ['id' => $id];
        //查询一条数据
        $return = $this->repoist->getOne($where, ['id', 'goods_id', 'goods_name', 'goods_code']);
        return $this->returnMsg(200, '查询成功', $return);
    }

    public function listss(Request $request)
    {
        $where = [];
        if (!empty($request->get('name'))) {
            $where['where'] = ['name' => $request->get('name')];
        }

        $return = $this->repoist->lists($where);
        return $return;
    }

    public function destroy(Request $request, $id)
    {
        if (!$id) {
            return $this->returnMsg(1, '请传递参数');
        }
        $where = [
            'id' => $id,
            'shop_id' => $request->user->shop_id
        ];
        return $this->repoist->del($where);
    }

    // 导入功能
    public function import(Request $request)
    {
        $model = new UploadRepository();
        $res = $model->upload($request, 'file');
        if (empty($res['file_src'])) {
            return [
                'code' => 100,
                'msg' => '上传失败',
                'fileName' => ''
            ];
        }
        $request['file_name'] = $res['file_name'];
        $request['upload_rout'] = $res['file_src'];

        return $this->repoist->add($request);
    }

    public function getDouYInOrderStatus()
    {
        return $this->repoist->getOrderStatus();
    }

    //导出
    public function getOrderExcel(Request $request)
    {
        // pageNum  pageSize
        $request->offsetSet('pageSize', 99999);
        $request->offsetSet('pageNum', 1);
        $resData = $this->index($request);
        if (empty($resData['data'])) {
            return $this->returnMsg(100, '下载的数据不能为空');
        }
        $model = new Excel();
        $title = [
            '订单编号',
            '上游编号',
            '下游编号',
            '来源',
            '分销商',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '省',
            '市',
            '区',
            '详细地址',
            '订单状态'
        ];
        $excelData = [];
        foreach ($resData['data'] as $key => $v) {
            $excelData[] = [
                $v['orderno'],
                $v['sup_orderno'],
                $v['dist_orderno'],
                $v['source'],
                $v['shop_str'],
                $v['pay_name'],
                $v['pay_phone'],
                $v['pay_identity'] . ' ',
                $v['post_province'],
                $v['post_city'],
                $v['post_area'],
                $v['post_address'],
                $v['status_desc'],
            ];
        }
        $fielname = '/attach/excel/' . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }

    public function catchDouyinThree(Request $request)
    {
        if (!$request->has('id')) {
            return $this->returnMsg(1, '参数不能为空');
        }
        $where = ['dist_orderno' => $request->get('id')];
        $oneData = $this->repoist->getOne($where);
        if (!$oneData) {
            return $this->returnMsg(2, '未查询到订单');
        }
        // 将用户提交到第三方
        $orderData = [
            'source' => 1,  // 数据来源
            // 'goods_code' => $oneData['goods_code'],
            // 'name' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_name'] : '',
            // 'identity' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['card_num'] : '',
            // 'contact' => ($resDouYinDetails['code'] == 200) ? $resDouYinDetail['user_phone'] : '',
            // 'province' => $resDouYinDetail['province'],
            // 'city' => $resDouYinDetail['city'],
            // 'area' => $resDouYinDetail['area'],
            // 'address' => (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . (($resDouYinDetails['code'] == 200) ? $resDouYinDetail['addr'] : ''),
            // 'shop_id' => $resDouYin->shop_id,
            // 'dist_orderno' => $resDouYinDetail['order_num'],
            // 'dist_id' => $resDouYin->id,
            // 'dist_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '',
            // 'author_id' => $resDouYinDetail['author_id'],
            // 'author_name' => $resDouYinDetail['author_name'],
            // 'remark' => $resDouYinDetail['c_biz_desc'],
        ];
        $orderData = json_decode(json_encode($oneData), true);
        $orderData['source'] = 1;
        if (!empty($orderData['id'])) {
            unset($orderData['id']);
        }
        if (!empty($orderData['douyin_id'])) {
            $orderData['source'] = 6;
            $orderData['shop_id'] = $orderData['douyin_id'];
        }
        // var_dump($orderData);
        // die();
        $model = new MainOrderRepostition();
        $res = $model->orderSubmit($orderData);
        $update['three_msg'] = !empty($res['msg']) ? $res['msg'] : '提交失败';
        if (!empty($res['code']) && $res['code'] == 200) {
            $update['status'] = 0;
        }
        $this->repoist->edit($where, $update);
        return $res;
    }

    public function catchOrderEditGoods(Request $request)
    {
        $params = $request->all();
        if (empty($params['user']['shop_id'])) {
            return $this->returnMsg(101, '请刷新页面重新提交');
        }
        if (empty($params['goods_id'])) {
            return $this->returnMsg(103, '请选择修改的商品');
        }
        if (empty($params['ids'])) {
            return $this->returnMsg(107, '请选择需要修改的订单');
        }
        // 查询商品 然后修改
        $goodsData = $this->goodsModel->getOne(['id' => $params['goods_id'], 'shop_id' => $params['user']['shop_id']], ['id', 'name', 'goods_code']);
        if (!$goodsData) {
            return $this->returnMsg(106, '未查到到商品');
        }

        $isSubmit = false;
        if (!empty($params['is_submit'])) {
            $isSubmit = true;
        }
        $isAll = true;
        foreach ($params['ids'] as $key => $val) {
            $where = [
                'dist_orderno' => $val,
                // 'goods_code' => $goodsData->goods_code,
            ];
            $update = [
                'goods_code' => $goodsData->goods_code,
                'three_msg' => '已提交'
            ];
            $isTrueOrder = $this->repoist->getOne($where);
            if ($isTrueOrder && $isTrueOrder->status < 50) {
                $isAll = false;
                continue;
            }
            $isTrue = $this->repoist->edit($where, $update);
            if ($isSubmit) {
                // 异步重新提交
                dispatch(new OrderSubmit(['dist_orderno' => $val], 'douyinNewSubmit'))->onQueue('TaskOrderSubmitDispose');
            }
        }
        if ($isAll) {
            return $this->returnMsg(200, '所有订单提交成功,目前运行中,请稍后查看订单');
        }
        return $this->returnMsg(200, '部分订单提交成功,目前运行中,请稍后查看订单');
    }
}
